package com.example.springboot_sdse_air.controller;

import com.example.springboot_sdse_air.common.Result;
import com.example.springboot_sdse_air.service.MinerULocalBatchService;
import com.example.springboot_sdse_air.service.MinerUService;
import com.example.springboot_sdse_air.service.ZipService;
import lombok.Getter;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：提供接口返回数据
 * 作者：王彬 202200111149
 * 日期：2025-04-08 11:49
 */
@RestController
@RequestMapping("/web")
public class WebController {

    @Resource
    MinerULocalBatchService minerULocalBatchService;

    @Resource
    ZipService zipService;

    @GetMapping("/hello")
    public Result hello(@RequestBody Integer integer) {
        return Result.success(integer);
    }

    @PostMapping("/post")
    public Result post(){
        return Result.success("post!");
    }

    @PostMapping("/MinerU_test2/{parentFolderName}/{fileName:.+}")
    public Result MinerU_test2(@PathVariable String parentFolderName,
                              @PathVariable String fileName,
                              @RequestParam Integer pdf_id) throws InterruptedException, IOException {
        String batchId = "48d1a475-d5bf-43b8-b7a9-2e4a0481fe0d";
        List<String> zipUrls = minerULocalBatchService.fetchExtractResultWithPolling(batchId);
        for(String zipUrl : zipUrls) {
            File zipFile = zipService.downloadZip(zipUrl, pdf_id);
            File destFolder = zipService.unzip(zipFile);
        }
        return Result.success();
    }

    @PostMapping("/MinerU_test/{parentFolderName}/{fileName:.+}")
    public Result MinerU_test(@PathVariable String parentFolderName,
                              @PathVariable String fileName,
                              @RequestParam Integer pdf_id) throws InterruptedException, IOException {
        // 拼接本地文件路径
        String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";
        String filePath = ROOT_PATH + File.separator + parentFolderName + File.separator + fileName;

        Map<String,Object> map = new HashMap<>();
        map.put("filePath",filePath);
        map.put("fileName",fileName);
        List<Map<String,Object>> list = new ArrayList<>();
        list.add(map);
        String batchId = minerULocalBatchService.getUrlsAndUploadFileBatch(list);
        List<String> zipUrls = minerULocalBatchService.fetchExtractResultWithPolling(batchId);
        for(String zipUrl : zipUrls) {
            File zipFile = zipService.downloadZip(zipUrl, pdf_id);
            File destFolder = zipService.unzip(zipFile);
        }
        return Result.success();
    }
}
